package cn.wen.javax.net.mail;

import java.io.File;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import cn.wen.javax.net.mail.base.HelperOfMail;

/**
 * Title：E-Mail 发送器（实现）
 * <p>
 * Description：基于Apache commons Email。
 * <p>
 * Copyright：Copyright (c) 2010-2012
 * 
 * @author <a href="mailto:ct_wen@qq.com">ctwen</a>, 温承瑭
 * @version Revision：1.0 Date：2012/8/2 Description：初完成。
 *          <p>
 */
public class MailSender implements IMailSender {

    private HtmlEmail sender;

    public HtmlEmail getSender() {
	return sender;
    }

    public void setSender(HtmlEmail sender) {
	this.sender = sender;
    }

    @Override
    public void send(IMailMessage mesg) throws MailException {
	try {
	    if (null != mesg.getFrom()) {
		sender.setFrom(mesg.getFrom(), getUserName(mesg.getFrom()));
	    }
	    if (null != mesg.getSubject()) {
		sender.setSubject(mesg.getSubject());
	    }
	    if (null != mesg.getText()) {
		sender.setHtmlMsg(mesg.getText());
	    }
	    if (null != mesg.getSentDate()) {
		sender.setSentDate(mesg.getSentDate());
	    }
	    for (String email : mesg.getReplyTo()) {
		sender.addReplyTo(email, getUserName(email));
	    }
	    for (String email : mesg.getTo()) {
		sender.addTo(email, getUserName(email));
	    }
	    for (String email : mesg.getCc()) {
		sender.addCc(email, getUserName(email));
	    }
	    for (String email : mesg.getBcc()) {
		sender.addBcc(email, getUserName(email));
	    }
	    for (File attach : mesg.getAttach()) {
		sender.attach(HelperOfMail.getEmailAttachment(attach));
	    }
	    sender.send();
	}
	catch (EmailException e) {
	    throw new MailException(e);
	}
	
	sender = null;
    }

    private String getUserName(String email) {
	return email.substring(0, email.indexOf("@"));
    }

}
